package balance_change_type

import (
	"context"
	"encoding/json"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/client/config"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetChangeLogLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 获取余额变动类型配置变更日志
func NewGetChangeLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetChangeLogLogic {
	return &GetChangeLogLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetChangeLogLogic) GetChangeLog(req *types.GetChangeLogReq) (resp *types.GetChangeLogReps, err error) {
	var reqData = config.GetConfigChangeLogReq{
		PageReq: &rpc.PageRequest{
			PageSize: req.PageSize,
			PageNo:   req.Page,
		},
	}
	result, err1 := l.svcCtx.AssetsRpc.Config.GetConfigChangeLog(l.ctx, &reqData)
	if err1 != nil {
		err = err1
		return
	}
	if len(result.List) == 0 {
		return nil, nil
	}
	var operateUids = make([]int64, 0)
	for _, row := range result.List {
		operateUids = append(operateUids, row.CreatedUid)
	}
	users, err := l.svcCtx.UserServiceRPC.UserGetAccountsByIds(l.ctx, &userrpc.UserSearchByIdsRequest{UserIds: operateUids})
	if err != nil {
		return nil, err
	}
	if users == nil || len(users.Accounts) == 0 {
		l.Logger.Infof("get user info error ")
		return nil, err
	}
	userMap := make(map[int64]*userrpc.User)
	for _, u := range users.Accounts {
		userMap[u.GetId()] = u
	}
	var retData []types.ChangeLog
	var oldValue types.GetBalanceChangeTypeList
	var newValue types.GetBalanceChangeTypeList

	for _, row := range result.List {
		err3 := json.Unmarshal([]byte(row.OldValue), &oldValue)
		if err3 != nil {
			oldValue = types.GetBalanceChangeTypeList{}
		}
		err4 := json.Unmarshal([]byte(row.NewValue), &newValue)
		if err4 != nil {
			newValue = types.GetBalanceChangeTypeList{}
		}
		retData = append(retData, types.ChangeLog{
			Id:          row.Id,
			Name:        row.Name,
			OldValue:    oldValue,
			NewValue:    newValue,
			OperateUser: userMap[row.CreatedUid].Account,
			OperateTime: row.CreateTime,
			Ip:          row.Ip,
			IpPlace:     row.IpPlace,
		})
	}
	resp = &types.GetChangeLogReps{
		List: retData,
		Pagination: types.Pagination{
			Page:      int32(req.Page),
			PageSize:  int32(req.PageSize),
			TotalPage: result.Pageination.GetTotalPage(),
			Total:     result.Pageination.GetTotal(),
		},
	}
	return
}
